package com.net2s.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jfree.util.Log;

import com.net2s.bbdd.UtilSQL;

/**
 * Servlet implementation class ServletCreateUSer
 */
public class ServletCreateUSer extends HttpServlet {
	private static final long serialVersionUID = 1L;
	static Logger log= Logger.getLogger(ServletCreateUSer.class);
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletCreateUSer() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		procesaPeticion(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		procesaPeticion(request,response);
	}

	private void procesaPeticion(HttpServletRequest request, HttpServletResponse response){

		if((request.getParameter("Consulta")!=null) && (request.getParameter("Marketing")!=null)){
			request.getSession().setAttribute("createUser","No se puede asignar al mismo usuario perfil de Consulta y Marketing");
			try{
			response.sendRedirect(response.encodeRedirectURL("CreateUser.jsp"));
			}catch(Exception e){
				
			}
		}
		else{	

			String query = "Insert into users(username,password,profile,nombre,apellidos,admin) " + 
			" values('" + request.getParameter("user") + "','" + request.getParameter("password") + "','";
			if(request.getParameter("Consulta")!=null)
				query=query + "Consulta','";
			else if (request.getParameter("Marketing")!=null)
				query = query + "Marketing','";


			query=query + request.getParameter("nombre") + "','" + request.getParameter("apellidos") + "','";

			if(request.getParameter("Administrador")!=null)
				query = query + "Y')";
			if(request.getParameter("Administrador")==null)
				query = query + "N')";

			log.info(query);
			try{
				UtilSQL.executeQuery(query);
				request.getSession().setAttribute("createUser","Usuario Creado Correctamente");


			}catch(Exception e){
				request.getSession().setAttribute("createUser", "Error al crear Usuario");
				log.error(e.getMessage());

			}
			try{
				response.sendRedirect(response.encodeRedirectURL("CreateUser.jsp"));
			}catch(Exception e){

			}
		}
	}

}
